package com.decoder;

import com.util.ByteUtil;
import com.util.InputCommandUtil;
import com.util.OutputCommandUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 保证每次ClientHandler每次接收到的数据都是一个完整的数据包。并将数据解析成16进制的字符串
 * create by zhaojing at 2019/5/22 15:03
 */
public class PacketDecoder extends ByteToMessageDecoder {
    StringBuilder sb=new StringBuilder();
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
        byte[] read =new byte[in.readableBytes()];
        in.readBytes(read);
        String packet = ByteUtil.BinaryToHexString(read).toUpperCase();
        System.out.println("ByteToMessageDecoder "+packet);
        sb.append(packet);
        if (!InputCommandUtil.isMasterCmd(packet) && !InputCommandUtil.isSlaveCmd(packet)) {
            return;
        }
        if (InputCommandUtil.isMasterCmd(packet) || InputCommandUtil.isSlaveCmd(packet)) {
            out.add(sb.toString());
            sb.setLength(0);
        }

    }
}
